import csv
from collections import Counter
import matplotlib
import matplotlib.pyplot as plt

matplotlib.use("Agg")
plt.rcParams["font.sans-serif"] = ["MiSans"]
plt.rcParams["axes.unicode_minus"] = False


def analyze_requests(csv_path, top_n=10):
    def generalize_path(path):
        # 修改后的路径分类逻辑：提取第一个目录
        parts = path.split('/')
        if len(parts) > 1 and parts[1]:  # 提取第一个有效目录
            return f"/{parts[1]}/*"
        return path  # 无目录结构则保持原样

    with open(csv_path, "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        # 应用新的路径处理规则 ↓
        paths = [generalize_path(row[1]) for row in reader if len(row) > 1]
    
    counter = Counter(paths)
    most_common = counter.most_common(top_n)
    labels = [item[0] for item in most_common]
    counts = [item[1] for item in most_common]

    # 新增平均值计算
    average = sum(counts) / len(counts) if counts else 0

    plt.figure(figsize=(12, 6))
    bars = plt.bar(labels, counts)
    
    # 新增平均值虚线标注
    plt.axhline(y=average, color='r', linestyle='--', label=f'平均值: {average:.1f}')
    plt.legend()
    plt.title("Top {} 异常请求统计".format(top_n))
    plt.xlabel("请求路径")
    plt.ylabel("访问次数")
    plt.xticks(rotation=45, ha="right")
    plt.subplots_adjust(bottom=0.3)
    for bar in bars:
        height = bar.get_height()
        plt.text(
            bar.get_x() + bar.get_width() / 2.0,
            height,
            f"{height}",
            ha="center",
            va="bottom",
        )

    plt.savefig("output.svg", format='svg')  # 输出矢量图
    plt.close()

    # 新增超过平均值目录输出
    over_average = [(path, count) for path, count in zip(labels, counts) if count > average]
    if over_average:
        print("\n超过平均值的请求路径：")
        for path, count in over_average:
            print(f"- {path}: {count}次")
    else:
        print("\n没有超过平均值的请求路径")


if __name__ == "__main__":
    file_path = "异常请求.csv"
    analyze_requests(file_path, 20)


# matplotlib.use("Agg")
# plt.rcParams["font.sans-serif"] = ["MiSans"]
# plt.rcParams["axes.unicode_minus"] = False

# def analyze_requests(csv_path, top_n=10):
#     with open(csv_path, "r", encoding="utf-8") as f:
#         reader = csv.reader(f)
#         paths = [row[1] for row in reader if len(row) > 1]
#     counter = Counter(paths)
#     most_common = counter.most_common(top_n)
#     labels = [item[0] for item in most_common]
#     counts = [item[1] for item in most_common]
#     plt.figure(figsize=(12, 6))
#     bars = plt.bar(labels, counts)
#     plt.title("Top {} 异常请求统计".format(top_n))
#     plt.xlabel("请求路径")
#     plt.ylabel("访问次数")
#     plt.xticks(rotation=45, ha="right")
#     plt.subplots_adjust(bottom=0.3)
#     for bar in bars:
#         height = bar.get_height()
#         plt.text(
#             bar.get_x() + bar.get_width() / 2.0,
#             height,
#             f"{height}",
#             ha="center",
#             va="bottom",
#         )

#     plt.savefig("output.svg", format='svg')
#     plt.close()

# if __name__ == "__main__":
#     file_path = "异常请求.csv"
#     analyze_requests(file_path, 20)